#include <yams/cli/completion_command.h>
#include <yams/cli/yams_cli.h>
#include <spdlog/spdlog.h>
#include <iostream>
#include <sstream>

namespace yams::cli {

std::string CompletionCommand::getName() const {
    return "completion";
}

std::string CompletionCommand::getDescription() const {
    return "Generate shell completion scripts for bash, zsh, and fish";
}

void CompletionCommand::registerCommand(CLI::App& app, YamsCLI* cli) {
    cli_ = cli;
    
    auto* cmd = app.add_subcommand("completion", getDescription());
    
    cmd->add_option("shell", shell_, "Shell type (bash, zsh, fish)")
        ->required()
        ->check(CLI::IsMember({"bash", "zsh", "fish"}));
    
    cmd->callback([this]() {
        auto result = execute();
        if (!result) {
            spdlog::error("Completion generation failed: {}", result.error().message);
            std::exit(1);
        }
    });
}

Result<void> CompletionCommand::execute() {
    try {
        std::string completionScript;
        
        if (shell_ == "bash") {
            completionScript = generateBashCompletion();
        } else if (shell_ == "zsh") {
            completionScript = generateZshCompletion();
        } else if (shell_ == "fish") {
            completionScript = generateFishCompletion();
        } else {
            return Error{ErrorCode::InvalidArgument, "Unsupported shell: " + shell_};
        }
        
        std::cout << completionScript << std::endl;
        return Result<void>();
        
    } catch (const std::exception& e) {
        return Error{ErrorCode::InternalError, 
                    std::string("Failed to generate completion: ") + e.what()};
    }
}

std::vector<std::string> CompletionCommand::getAvailableCommands() const {
    // Keep in sync with command list in yams_cli.cpp:105
    return {
        "init", "add", "get", "delete", "list", "search", "config", 
        "auth", "stats", "uninstall", "migrate", "update", "browse", "serve", "completion"
    };
}

std::vector<std::string> CompletionCommand::getGlobalFlags() const {
    return {
        "--help", "-h", "--version", "--data-dir", "--storage", 
        "--verbose", "-v", "--json", "--help-all"
    };
}

std::string CompletionCommand::generateBashCompletion() const {
    std::ostringstream oss;
    
    oss << "#!/bin/bash\n";
    oss << "# Bash completion script for YAMS CLI\n";
    oss << "# Generated by: yams completion bash\n";
    oss << "\n";
    oss << "# Safety: provide minimal fallbacks if bash-completion isn't loaded\n";
    oss << "if ! declare -F _init_completion >/dev/null 2>&1; then\n";
    oss << "  _init_completion() { cur=\"${COMP_WORDS[COMP_CWORD]}\"; prev=\"${COMP_WORDS[COMP_CWORD-1]}\"; words=(${COMP_WORDS[@]}); cword=${COMP_CWORD}; }\n";
    oss << "fi\n";
    oss << "if ! declare -F _filedir >/dev/null 2>&1; then\n";
    oss << "  _filedir() { COMPREPLY=(); }\n";
    oss << "fi\n\n";
    
    oss << "_yams_completion() {\n";
    oss << "    local cur prev words cword\n";
    oss << "    _init_completion || return\n";
    oss << "\n";
    
    // Global flags
    oss << "    local global_flags=\"";
    for (const auto& flag : getGlobalFlags()) {
        oss << flag << " ";
    }
    oss << "\"\n";
    
    // Commands
    oss << "    local commands=\"";
    for (const auto& cmd : getAvailableCommands()) {
        oss << cmd << " ";
    }
    oss << "\"\n\n";
    
    // Main completion logic
    oss << "    # Complete subcommands\n";
    oss << "    if [[ $cword -eq 1 ]]; then\n";
    oss << "        COMPREPLY=($(compgen -W \"$commands\" -- \"$cur\"))\n";
    oss << "        return 0\n";
    oss << "    fi\n\n";
    
    // Command-specific completions
    oss << "    # Handle command-specific completions\n";
    oss << "    local command=\"${words[1]}\"\n";
    oss << "    case \"$command\" in\n";
    
    // Add command
    oss << "        add)\n";
    oss << "            case \"$prev\" in\n";
    oss << "                --name|--tags|--metadata)\n";
    oss << "                    # No completion for these options\n";
    oss << "                    return 0\n";
    oss << "                    ;;\n";
    oss << "                *)\n";
    oss << "                    local add_flags=\"--name --tags --metadata --snapshot-id --help\"\n";
    oss << "                    if [[ $cur == -* ]]; then\n";
    oss << "                        COMPREPLY=($(compgen -W \"$add_flags $global_flags\" -- \"$cur\"))\n";
    oss << "                    else\n";
    oss << "                        # Complete file paths\n";
    oss << "                        _filedir\n";
    oss << "                    fi\n";
    oss << "                    ;;\n";
    oss << "            esac\n";
    oss << "            ;;\n";
    
    // Get command  
    oss << "        get)\n";
    oss << "            case \"$prev\" in\n";
    oss << "                --output)\n";
    oss << "                    _filedir\n";
    oss << "                    return 0\n";
    oss << "                    ;;\n";
    oss << "                --type|--mime|--extension)\n";
    oss << "                    # No specific completion for these\n";
    oss << "                    return 0\n";
    oss << "                    ;;\n";
    oss << "                *)\n";
    oss << "                    local get_flags=\"--output --type --mime --extension --binary --text --created-after --created-before --modified-after --modified-before --indexed-after --indexed-before --help\"\n";
    oss << "                    if [[ $cur == -* ]]; then\n";
    oss << "                        COMPREPLY=($(compgen -W \"$get_flags $global_flags\" -- \"$cur\"))\n";
    oss << "                    fi\n";
    oss << "                    ;;\n";
    oss << "            esac\n";
    oss << "            ;;\n";
    
    // List command
    oss << "        list)\n";
    oss << "            case \"$prev\" in\n";
    oss << "                --format)\n";
    oss << "                    COMPREPLY=($(compgen -W \"table json csv minimal\" -- \"$cur\"))\n";
    oss << "                    return 0\n";
    oss << "                    ;;\n";
    oss << "                --sort)\n";
    oss << "                    COMPREPLY=($(compgen -W \"name size date hash\" -- \"$cur\"))\n";
    oss << "                    return 0\n";
    oss << "                    ;;\n";
    oss << "                --type|--mime|--extension)\n";
    oss << "                    return 0\n";
    oss << "                    ;;\n";
    oss << "                *)\n";
    oss << "                    local list_flags=\"--format --sort --reverse --limit --type --mime --extension --binary --text --created-after --created-before --modified-after --modified-before --indexed-after --indexed-before --help\"\n";
    oss << "                    if [[ $cur == -* ]]; then\n";
    oss << "                        COMPREPLY=($(compgen -W \"$list_flags $global_flags\" -- \"$cur\"))\n";
    oss << "                    fi\n";
    oss << "                    ;;\n";
    oss << "            esac\n";
    oss << "            ;;\n";
    
    // Grep command
    oss << "        grep)\n";
    oss << "            case \"$prev\" in\n";
    oss << "                --color)\n";
    oss << "                    COMPREPLY=($(compgen -W \"always never auto\" -- \"$cur\"))\n";
    oss << "                    return 0\n";
    oss << "                    ;;\n";
    oss << "                *)\n";
    oss << "                    local grep_flags=\"-A --after -B --before -C --context -i --ignore-case -w --word -v --invert -n --line-numbers -H --with-filename --no-filename -c --count -l --files-with-matches -L --files-without-match --color -m --max-count --limit --help\"\n";
    oss << "                    if [[ $cur == -* ]]; then\n";
    oss << "                        COMPREPLY=($(compgen -W \"$grep_flags $global_flags\" -- \"$cur\"))\n";
    oss << "                    else\n";
    oss << "                        _filedir\n";
    oss << "                    fi\n";
    oss << "                    ;;\n";
    oss << "            esac\n";
    oss << "            ;;\n";
    
    // Stats command
    oss << "        stats)\n";
    oss << "            case \"$prev\" in\n";
    oss << "                --format)\n";
    oss << "                    COMPREPLY=($(compgen -W \"text json\" -- \"$cur\"))\n";
    oss << "                    return 0\n";
    oss << "                    ;;\n";
    oss << "                *)\n";
    oss << "                    local stats_flags=\"--format --help\"\n";
    oss << "                    COMPREPLY=($(compgen -W \"$stats_flags $global_flags\" -- \"$cur\"))\n";
    oss << "                    ;;\n";
    oss << "            esac\n";
    oss << "            ;;\n";
    
    // Config command
    oss << "        config)\n";
    oss << "            case \"$prev\" in\n";
    oss << "                --format)\n";
    oss << "                    COMPREPLY=($(compgen -W \"toml json\" -- \"$cur\"))\n";
    oss << "                    return 0\n";
    oss << "                    ;;\n";
    oss << "                *)\n";
    oss << "                    local config_flags=\"--format --help\"\n";
    oss << "                    COMPREPLY=($(compgen -W \"$config_flags $global_flags\" -- \"$cur\"))\n";
    oss << "                    ;;\n";
    oss << "            esac\n";
    oss << "            ;;\n";
    
    // Auth command
    oss << "        auth)\n";
    oss << "            case \"$prev\" in\n";
    oss << "                --key-type)\n";
    oss << "                    COMPREPLY=($(compgen -W \"ed25519 rsa\" -- \"$cur\"))\n";
    oss << "                    return 0\n";
    oss << "                    ;;\n";
    oss << "                --format)\n";
    oss << "                    COMPREPLY=($(compgen -W \"table json\" -- \"$cur\"))\n";
    oss << "                    return 0\n";
    oss << "                    ;;\n";
    oss << "                *)\n";
    oss << "                    local auth_flags=\"--key-type --output --format --validity --key-name --help\"\n";
    oss << "                    COMPREPLY=($(compgen -W \"$auth_flags $global_flags\" -- \"$cur\"))\n";
    oss << "                    ;;\n";
    oss << "            esac\n";
    oss << "            ;;\n";
    
    // Completion command
    oss << "        completion)\n";
    oss << "            if [[ $cword -eq 2 ]]; then\n";
    oss << "                COMPREPLY=($(compgen -W \"bash zsh fish\" -- \"$cur\"))\n";
    oss << "            else\n";
    oss << "                COMPREPLY=($(compgen -W \"--help\" -- \"$cur\"))\n";
    oss << "            fi\n";
    oss << "            ;;\n";
    
    // Default case
    oss << "        *)\n";
    oss << "            # For other commands, just complete global flags\n";
    oss << "            if [[ $cur == -* ]]; then\n";
    oss << "                COMPREPLY=($(compgen -W \"$global_flags\" -- \"$cur\"))\n";
    oss << "            fi\n";
    oss << "            ;;\n";
    oss << "    esac\n";
    oss << "}\n\n";
    
    // Register the completion function
    oss << "# Register completion for yams command\n";
    oss << "complete -F _yams_completion yams\n";
    
    return oss.str();
}

std::string CompletionCommand::generateZshCompletion() const {
    std::ostringstream oss;
    
    oss << "#compdef yams\n";
    oss << "# Zsh completion script for YAMS CLI\n";
    oss << "# Generated by: yams completion zsh\n";
    oss << "\n";
    oss << "[[ -n ${ZSH_VERSION:-} ]] || return\n";
    oss << "if ! typeset -f compinit >/dev/null 2>&1; then\n";
    oss << "  autoload -U compinit\n";
    oss << "  compinit -C\n";
    oss << "fi\n\n";
    oss << "if ! type _arguments >/dev/null 2>&1; then\n";
    oss << "  _arguments() { return 0 }\n";
    oss << "fi\n\n";
    
    oss << "_yams() {\n";
    oss << "    local context state state_descr line\n";
    oss << "    typeset -A opt_args\n\n";
    
    oss << "    local global_flags=(\n";
    for (const auto& flag : getGlobalFlags()) {
        if (flag == "--help" || flag == "-h") {
            oss << "        '(-h --help)'{-h,--help}'[Show help information]'\n";
        } else if (flag == "--verbose" || flag == "-v") {
            oss << "        '(-v --verbose)'{-v,--verbose}'[Enable verbose output]'\n";
        } else if (flag == "--version") {
            oss << "        '--version[Show version information]'\n";
        } else if (flag == "--data-dir") {
            oss << "        '--data-dir[Data directory for storage]:directory:_directories'\n";
        } else if (flag == "--storage") {
            oss << "        '--storage[Data directory for storage]:directory:_directories'\n";
        } else if (flag == "--json") {
            oss << "        '--json[Output in JSON format]'\n";
        } else if (flag == "--help-all") {
            oss << "        '--help-all[Show extended help]'\n";
        }
    }
    oss << "    )\n\n";
    
    oss << "    _arguments -C \\\n";
    oss << "        \"$global_flags[@]\" \\\n";
    oss << "        '1: :_yams_commands' \\\n";
    oss << "        '*:: :->args'\n\n";
    
    oss << "    case $state in\n";
    oss << "        args)\n";
    oss << "            case $words[1] in\n";
    
    // Add command
    oss << "                add)\n";
    oss << "                    _arguments \\\n";
    oss << "                        '--name[Name for the content]:name:' \\\n";
    oss << "                        '--tags[Tags for the content]:tags:' \\\n";
    oss << "                        '--metadata[Additional metadata]:metadata:' \\\n";
    oss << "                        '--snapshot-id[Snapshot ID]:id:' \\\n";
    oss << "                        '*:file:_files'\n";
    oss << "                    ;;\n";
    
    // Get command
    oss << "                get)\n";
    oss << "                    _arguments \\\n";
    oss << "                        '--output[Output file]:file:_files' \\\n";
    oss << "                        '--type[File type filter]:type:' \\\n";
    oss << "                        '--mime[MIME type filter]:mime:' \\\n";
    oss << "                        '--extension[Extension filter]:extension:' \\\n";
    oss << "                        '--binary[Binary files only]' \\\n";
    oss << "                        '--text[Text files only]' \\\n";
    oss << "                        '--created-after[Created after]:date:' \\\n";
    oss << "                        '--created-before[Created before]:date:' \\\n";
    oss << "                        '--modified-after[Modified after]:date:' \\\n";
    oss << "                        '--modified-before[Modified before]:date:' \\\n";
    oss << "                        '--indexed-after[Indexed after]:date:' \\\n";
    oss << "                        '--indexed-before[Indexed before]:date:'\n";
    oss << "                    ;;\n";
    
    // List command
    oss << "                list)\n";
    oss << "                    _arguments \\\n";
    oss << "                        '--format[Output format]:format:(table json csv minimal)' \\\n";
    oss << "                        '--sort[Sort by]:sort:(name size date hash)' \\\n";
    oss << "                        '--reverse[Reverse sort order]' \\\n";
    oss << "                        '--limit[Limit results]:limit:' \\\n";
    oss << "                        '--type[File type filter]:type:' \\\n";
    oss << "                        '--mime[MIME type filter]:mime:' \\\n";
    oss << "                        '--extension[Extension filter]:extension:' \\\n";
    oss << "                        '--binary[Binary files only]' \\\n";
    oss << "                        '--text[Text files only]' \\\n";
    oss << "                        '--created-after[Created after]:date:' \\\n";
    oss << "                        '--created-before[Created before]:date:' \\\n";
    oss << "                        '--modified-after[Modified after]:date:' \\\n";
    oss << "                        '--modified-before[Modified before]:date:' \\\n";
    oss << "                        '--indexed-after[Indexed after]:date:' \\\n";
    oss << "                        '--indexed-before[Indexed before]:date:'\n";
    oss << "                    ;;\n";
    
    // Grep command
    oss << "                grep)\n";
    oss << "                    _arguments \\\n";
    oss << "                        '(-A --after)'{-A,--after}'[Show N lines after match]:N:' \\\n";
    oss << "                        '(-B --before)'{-B,--before}'[Show N lines before match]:N:' \\\n";
    oss << "                        '(-C --context)'{-C,--context}'[Show N lines before and after match]:N:' \\\n";
    oss << "                        '(-i --ignore-case)'{-i,--ignore-case}'[Case-insensitive search]' \\\n";
    oss << "                        '(-w --word)'{-w,--word}'[Match whole words only]' \\\n";
    oss << "                        '(-v --invert)'{-v,--invert}'[Invert match]' \\\n";
    oss << "                        '(-n --line-numbers)'{-n,--line-numbers}'[Show line numbers]' \\\n";
    oss << "                        '(-H --with-filename)'{-H,--with-filename}'[Show filename with matches]' \\\n";
    oss << "                        '--no-filename[Never show filename]' \\\n";
    oss << "                        '(-c --count)'{-c,--count}'[Show only count of matching lines]' \\\n";
    oss << "                        '(-l --files-with-matches)'{-l,--files-with-matches}'[Show only filenames with matches]' \\\n";
    oss << "                        '(-L --files-without-match)'{-L,--files-without-match}'[Show only filenames without matches]' \\\n";
    oss << "                        '--color[Color mode]:mode:(always never auto)' \\\n";
    oss << "                        '(-m --max-count)'{-m,--max-count}'[Stop after N matches per file]:N:' \\\n";
    oss << "                        '--limit[Alias of --max-count]:N:' \\\n";
    oss << "                        '*:file:_files'\n";
    oss << "                    ;;\n";
    
    // Stats command
    oss << "                stats)\n";
    oss << "                    _arguments \\\n";
    oss << "                        '--format[Output format]:format:(text json)'\n";
    oss << "                    ;;\n";
    
    // Config command
    oss << "                config)\n";
    oss << "                    _arguments \\\n";
    oss << "                        '--format[Output format]:format:(toml json)'\n";
    oss << "                    ;;\n";
    
    // Auth command
    oss << "                auth)\n";
    oss << "                    _arguments \\\n";
    oss << "                        '--key-type[Key type]:type:(ed25519 rsa)' \\\n";
    oss << "                        '--output[Output directory]:directory:_directories' \\\n";
    oss << "                        '--format[Output format]:format:(table json)' \\\n";
    oss << "                        '--validity[Token validity]:validity:' \\\n";
    oss << "                        '--key-name[Key name]:name:'\n";
    oss << "                    ;;\n";
    
    // Completion command
    oss << "                completion)\n";
    oss << "                    _arguments '1:shell:(bash zsh fish)'\n";
    oss << "                    ;;\n";
    
    oss << "            esac\n";
    oss << "            ;;\n";
    oss << "    esac\n";
    oss << "}\n\n";
    
    oss << "_yams_commands() {\n";
    oss << "    local commands\n";
    oss << "    commands=(\n";
    for (const auto& cmd : getAvailableCommands()) {
        oss << "        '" << cmd << ":";
        if (cmd == "init") oss << "Initialize YAMS storage and configuration";
        else if (cmd == "add") oss << "Add files or content to YAMS";
        else if (cmd == "get") oss << "Retrieve content by hash";
        else if (cmd == "delete") oss << "Delete content from YAMS";
        else if (cmd == "list") oss << "List stored content";
        else if (cmd == "search") oss << "Search stored content";
        else if (cmd == "config") oss << "Show or modify configuration";
        else if (cmd == "auth") oss << "Authentication and key management";
        else if (cmd == "stats") oss << "Show storage statistics";
        else if (cmd == "uninstall") oss << "Uninstall YAMS";
        else if (cmd == "migrate") oss << "Run database migrations";
        else if (cmd == "update") oss << "Update stored content";
        else if (cmd == "browse") oss << "Browse content interactively";
        else if (cmd == "serve") oss << "Start MCP server";
        else if (cmd == "completion") oss << "Generate shell completion scripts";
        oss << "'\n";
    }
    oss << "    )\n";
    oss << "    _describe 'commands' commands\n";
    oss << "}\n\n";
    
    return oss.str();
}

std::string CompletionCommand::generateFishCompletion() const {
    std::ostringstream oss;
    
    oss << "# Fish completion script for YAMS CLI\n";
    oss << "# Generated by: yams completion fish\n";
    oss << "\n";
    
    // Function to check if we're completing a specific command
    oss << "function __fish_yams_using_command\n";
    oss << "    set cmd (commandline -opc)\n";
    oss << "    if [ (count $cmd) -gt 1 ]; and [ $cmd[2] = $argv[1] ]\n";
    oss << "        return 0\n";
    oss << "    end\n";
    oss << "    return 1\n";
    oss << "end\n\n";
    
    // Global options
    oss << "# Global options\n";
    oss << "complete -c yams -s h -l help -d 'Show help information'\n";
    oss << "complete -c yams -l version -d 'Show version information'\n";
    oss << "complete -c yams -s v -l verbose -d 'Enable verbose output'\n";
    oss << "complete -c yams -l json -d 'Output in JSON format'\n";
    oss << "complete -c yams -l data-dir -d 'Data directory for storage' -r\n";
    oss << "complete -c yams -l storage -d 'Data directory for storage' -r\n";
    oss << "complete -c yams -l help-all -d 'Show extended help'\n\n";
    
    // Subcommands
    oss << "# Subcommands\n";
    for (const auto& cmd : getAvailableCommands()) {
        oss << "complete -c yams -f -n '__fish_use_subcommand' -a " << cmd;
        if (cmd == "init") oss << " -d 'Initialize YAMS storage and configuration'";
        else if (cmd == "add") oss << " -d 'Add files or content to YAMS'";
        else if (cmd == "get") oss << " -d 'Retrieve content by hash'";
        else if (cmd == "delete") oss << " -d 'Delete content from YAMS'";
        else if (cmd == "list") oss << " -d 'List stored content'";
        else if (cmd == "search") oss << " -d 'Search stored content'";
        else if (cmd == "config") oss << " -d 'Show or modify configuration'";
        else if (cmd == "auth") oss << " -d 'Authentication and key management'";
        else if (cmd == "stats") oss << " -d 'Show storage statistics'";
        else if (cmd == "uninstall") oss << " -d 'Uninstall YAMS'";
        else if (cmd == "migrate") oss << " -d 'Run database migrations'";
        else if (cmd == "update") oss << " -d 'Update stored content'";
        else if (cmd == "browse") oss << " -d 'Browse content interactively'";
        else if (cmd == "serve") oss << " -d 'Start MCP server'";
        else if (cmd == "completion") oss << " -d 'Generate shell completion scripts'";
        oss << "\n";
    }
    oss << "\n";
    
    // Command-specific completions
    
    // Add command
    oss << "# add command\n";
    oss << "complete -c yams -f -n '__fish_yams_using_command add' -l name -d 'Name for the content' -r\n";
    oss << "complete -c yams -f -n '__fish_yams_using_command add' -l tags -d 'Tags for the content' -r\n";
    oss << "complete -c yams -f -n '__fish_yams_using_command add' -l metadata -d 'Additional metadata' -r\n";
    oss << "complete -c yams -f -n '__fish_yams_using_command add' -l snapshot-id -d 'Snapshot ID' -r\n\n";
    
    // Get command
    oss << "# get command\n";
    oss << "complete -c yams -f -n '__fish_yams_using_command get' -l output -d 'Output file' -r\n";
    oss << "complete -c yams -f -n '__fish_yams_using_command get' -l type -d 'File type filter' -r\n";
    oss << "complete -c yams -f -n '__fish_yams_using_command get' -l mime -d 'MIME type filter' -r\n";
    oss << "complete -c yams -f -n '__fish_yams_using_command get' -l extension -d 'Extension filter' -r\n";
    oss << "complete -c yams -f -n '__fish_yams_using_command get' -l binary -d 'Binary files only'\n";
    oss << "complete -c yams -f -n '__fish_yams_using_command get' -l text -d 'Text files only'\n";
    oss << "complete -c yams -f -n '__fish_yams_using_command get' -l created-after -d 'Created after' -r\n";
    oss << "complete -c yams -f -n '__fish_yams_using_command get' -l created-before -d 'Created before' -r\n";
    oss << "complete -c yams -f -n '__fish_yams_using_command get' -l modified-after -d 'Modified after' -r\n";
    oss << "complete -c yams -f -n '__fish_yams_using_command get' -l modified-before -d 'Modified before' -r\n";
    oss << "complete -c yams -f -n '__fish_yams_using_command get' -l indexed-after -d 'Indexed after' -r\n";
    oss << "complete -c yams -f -n '__fish_yams_using_command get' -l indexed-before -d 'Indexed before' -r\n\n";
    
    // List command
    oss << "# list command\n";
    oss << "complete -c yams -f -n '__fish_yams_using_command list' -l format -d 'Output format' -a 'table json csv minimal'\n";
    oss << "complete -c yams -f -n '__fish_yams_using_command list' -l sort -d 'Sort by' -a 'name size date hash'\n";
    oss << "complete -c yams -f -n '__fish_yams_using_command list' -l reverse -d 'Reverse sort order'\n";
    oss << "complete -c yams -f -n '__fish_yams_using_command list' -l limit -d 'Limit results' -r\n";
    oss << "complete -c yams -f -n '__fish_yams_using_command list' -l type -d 'File type filter' -r\n";
    oss << "complete -c yams -f -n '__fish_yams_using_command list' -l mime -d 'MIME type filter' -r\n";
    oss << "complete -c yams -f -n '__fish_yams_using_command list' -l extension -d 'Extension filter' -r\n";
    oss << "complete -c yams -f -n '__fish_yams_using_command list' -l binary -d 'Binary files only'\n";
    oss << "complete -c yams -f -n '__fish_yams_using_command list' -l text -d 'Text files only'\n";
    oss << "complete -c yams -f -n '__fish_yams_using_command list' -l created-after -d 'Created after' -r\n";
    oss << "complete -c yams -f -n '__fish_yams_using_command list' -l created-before -d 'Created before' -r\n";
    oss << "complete -c yams -f -n '__fish_yams_using_command list' -l modified-after -d 'Modified after' -r\n";
    oss << "complete -c yams -f -n '__fish_yams_using_command list' -l modified-before -d 'Modified before' -r\n";
    oss << "complete -c yams -f -n '__fish_yams_using_command list' -l indexed-after -d 'Indexed after' -r\n";
    oss << "complete -c yams -f -n '__fish_yams_using_command list' -l indexed-before -d 'Indexed before' -r\n\n";
    
    // Grep command
    oss << "# grep command\n";
    oss << "complete -c yams -f -n '__fish_yams_using_command grep' -l after -s A -d 'Show N lines after match' -r\n";
    oss << "complete -c yams -f -n '__fish_yams_using_command grep' -l before -s B -d 'Show N lines before match' -r\n";
    oss << "complete -c yams -f -n '__fish_yams_using_command grep' -l context -s C -d 'Show N lines before and after match' -r\n";
    oss << "complete -c yams -f -n '__fish_yams_using_command grep' -l ignore-case -s i -d 'Case-insensitive search'\n";
    oss << "complete -c yams -f -n '__fish_yams_using_command grep' -l word -s w -d 'Match whole words only'\n";
    oss << "complete -c yams -f -n '__fish_yams_using_command grep' -l invert -s v -d 'Invert match'\n";
    oss << "complete -c yams -f -n '__fish_yams_using_command grep' -l line-numbers -s n -d 'Show line numbers'\n";
    oss << "complete -c yams -f -n '__fish_yams_using_command grep' -l with-filename -s H -d 'Show filename with matches'\n";
    oss << "complete -c yams -f -n '__fish_yams_using_command grep' -l no-filename -d 'Never show filename'\n";
    oss << "complete -c yams -f -n '__fish_yams_using_command grep' -l count -s c -d 'Show only count of matching lines'\n";
    oss << "complete -c yams -f -n '__fish_yams_using_command grep' -l files-with-matches -s l -d 'Show only filenames with matches'\n";
    oss << "complete -c yams -f -n '__fish_yams_using_command grep' -l files-without-match -s L -d 'Show only filenames without matches'\n";
    oss << "complete -c yams -f -n '__fish_yams_using_command grep' -l color -d 'Color mode' -a 'always never auto'\n";
    oss << "complete -c yams -f -n '__fish_yams_using_command grep' -l max-count -s m -d 'Stop after N matches per file' -r\n";
    oss << "complete -c yams -f -n '__fish_yams_using_command grep' -l limit -d 'Alias of --max-count' -r\n\n";
    
    // Stats command
    oss << "# stats command\n";
    oss << "complete -c yams -f -n '__fish_yams_using_command stats' -l format -d 'Output format' -a 'text json'\n\n";
    
    // Config command
    oss << "# config command\n";
    oss << "complete -c yams -f -n '__fish_yams_using_command config' -l format -d 'Output format' -a 'toml json'\n\n";
    
    // Auth command
    oss << "# auth command\n";
    oss << "complete -c yams -f -n '__fish_yams_using_command auth' -l key-type -d 'Key type' -a 'ed25519 rsa'\n";
    oss << "complete -c yams -f -n '__fish_yams_using_command auth' -l output -d 'Output directory' -r\n";
    oss << "complete -c yams -f -n '__fish_yams_using_command auth' -l format -d 'Output format' -a 'table json'\n";
    oss << "complete -c yams -f -n '__fish_yams_using_command auth' -l validity -d 'Token validity' -r\n";
    oss << "complete -c yams -f -n '__fish_yams_using_command auth' -l key-name -d 'Key name' -r\n\n";
    
    // Completion command
    oss << "# completion command\n";
    oss << "complete -c yams -f -n '__fish_yams_using_command completion' -a 'bash zsh fish' -d 'Shell type'\n";
    
    return oss.str();
}

// Factory function
std::unique_ptr<ICommand> createCompletionCommand() {
    return std::make_unique<CompletionCommand>();
}

} // namespace yams::cli
